package com.travellightly.listener;

import com.travellightly.base.exception.ServiceException;
import com.travellightly.base.result.Codes;
import com.travellightly.base.result.R;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * 全局异常处理
 *
 * @author songjiahao
 * @date 2023/04/17  13:00
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public R exceptionHandler(Exception e){
        e.printStackTrace();
        return R.error(Codes.ERROR);
    }
    @ExceptionHandler(ServiceException.class)
    public R serviceExceptionHandler(ServiceException e){
        return R.error(e.getCodes());
    }
    @ExceptionHandler(BindException.class)
    public R bindExceptionHandler(BindException e){
        List<ObjectError> allErrors = e.getAllErrors();
        List<String> emag = new ArrayList<>();
        for (ObjectError error : allErrors) {
            emag.add(error.getDefaultMessage());
        }
        return R.error(Codes.BIND_ERROR,emag);
    }
}
